(function ($) {

})(window.jQuery);

    var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table,
        $ = layui.jquery,fid, id = getQueryVariable("id"),wxandbhflag="",
        imgs=[],wjs=[];//
         var productList=[];//产品列表
         var peijianList=[];//配件列表
         var feiyong=[];//费用
         var fujian=[];//附件
         var businessMode="";//业务模式

         var parentCustomerCode="";//客户编码
         var parentCurrencyCode="";//币种编码
         var parentPriceTermsCode="";//价格术语编码
         var costTypeList = [];  //未停用直接费用类型
         var costTypeListAll = getdictionary(5,19);  //全部直接费用类型
        for (let i in costTypeListAll) {
            if (costTypeListAll[i].valid==1){
                costTypeList.push(costTypeListAll[i]);
            }
        }
        var contractNoList=[];//产品对应的外销合同号集合


var impcustomerCode="";//客户编码
var impcustomerName="";//客户名称
var xshth=[];//主信息中的拼接后的销售合同号

//业务员集合
let salesmanList=[];
$(".customerLevelCodeHin").hide();
$("").keydown(function (e) {
    if (e.keyCode === 13) {
        $("#queryCondBtn").trigger("click");
    }
});
//操作员
form.val("editor-form", {
    "executorCode":user.code,
    "executorName":user.name,
    "invoiceAmount":0
});
// select下拉框选中触发事件
form.on("select(signingcompany)", function(data){

   // alert(data.value); // 获取选中的值
    getBank(data.value);
});
var fpzje=getAllRolesByCurr("shipmentplan_newupshipmentplan");//判断是否有此角色，出运计划-发票总额 显示权限
var ywbqx=getAllRolesByCurr("shipmentplan_newupshipmentplan_ywb");//判断是否有此角色
//下拉框
getlxandlevel();
////获取公司、客户名称
setPullMenu();
//获取货柜型号
getContainerModel();

//判断当前登录用户是否为 营销部门的总监 角色 true:是 false 否
let isMarketingDirector=false;
is_marketing_director();
if (isMarketingDirector){
    $("#priceTerm").attr("disabled",false);
    form.render();
}
let isContainsRoleShipPlan=false;
getIsContainsRoleShipPlan();
if (!isContainsRoleShipPlan){
    document.getElementById("logLi").style.display = "none";
}
//判断当前登录用户是否为 营销部门的总监 管理员角色 true:是 false 否
let isMarketingDirectorMsn="是";
is_marketing_director_msn();
if (isMarketingDirectorMsn=="否"){
    $("#submitT").hide();
}
//表单初始值，修改时调用
if (id != ""){
    wxandbhflag="all";
    // $("input[name='shipmentNo']").attr("readOnly",true);
    $("input[name='customerCode']").attr("readOnly",true);

    $("input[name='customerLevelCode']").attr("readOnly",true);
    $("input[name='customerLevelName']").attr("readOnly",true);



    queryByid(id);//获取出运计划主信息
    getProdcuInfo();//获取产品列表
    getfeiyong();//获取费用
    getfujian();//获取文件附件

}

lay('.starttime').each(function(){
    if(id == ""){
        laydate.render({
            elem: this,
           // max: 0,//最大值为当前日期
            eventElem: '#starttime',//日期输入框的图标，给图标也绑定点击事件
            trigger: 'click'
            ,value: new Date() //默认值30天前
        });
    }

});

//监听货柜型号下拉框
form.on("select(containerTypeCode)", function(data){
    if(data.value === ""){
        $('#containerType').val("");
        return;
    }
    for(let i in containerModel){
        if(data.value == containerModel[i].code){
            $('#containerType').val(containerModel[i].name);
        }
    }
});
//监听业务员下拉框
form.on("select(salesmanFilter)", function(data){
    for(let i in salesmanList){
        if(data.value == salesmanList[i].code){
            $('#salesmanName').val(salesmanList[i].name);
            break;
        }
    }
});


//监听提交
    form.on('submit(form-element)', function (data) {
      if(isShipmentNo(data.field.shipmentNo)){
          layer.msg('出运单号已存在！');
      }else{
          data.field.boxStatus="3";
          let msgFlag=save(data.field);
          if (msgFlag==="true"){
              layer.msg("提交成功！！");
          }else {
              layer.msg(msgFlag);
          }

      }
        return false;
    });
    form.on('submit(form-element-save)', function (data) {
        if(isShipmentNo(data.field.shipmentNo)){
            layer.msg('出运单号已存在！');
        }else{
            data.field.boxStatus="1";
            let msgFlag=save(data.field);
            if (msgFlag==="true"){
                layer.msg("提交成功！！");
            }else {
                layer.msg(msgFlag);
            }
        }
        return false;
    });
    //判断 单号是否重复
    function isShipmentNo(shipmentNo){
        let arrays=findShipmentPlanByCode(shipmentNo);
        let flag=false;
        for (let i in arrays) {
            if (id==""){
                flag=true;
            }
            if (arrays[i].id!=id && id!=""){
                flag=true;
            }
        }
        return flag;
    }
    function findShipmentPlanByCode(da){
        let data;
        $.ajax({
            type : 'GET',
            data:{"code":da},
            url:'shipmentPlan/shipmentPlanCodeIsExit',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    data=da.data;
                }
            }
        });
        return data;
    }

//--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid'
        ,data:productList,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true, fixed: true, totalRowText: '合计'},
            {field: 'img', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},//, templet: '#imgTpl'
            {field: 'purchaseNo', width: 120, title: '采购单号'},
            {field: 'customerContractNo', width: 120, title: '客户合同号' },
            {field: 'exportContractNo', width: 120, title: '外销合同号' },
            {field: 'productNo', width: 220, title: '产品编码'},//, templet:'#productcodeselect'
            {field: 'specNo', width: 120, title: '规格编码' },
            {field: 'normExplain', width: 120, title: '规格说明' },
            {field: 'customerContractNo', width: 120, title: '客户货号' },
            {field: 'chineseName', width: 120, title: '中文名称' },
            {field: 'englishName', width: 120, title: '英文名称'},
            {field: 'chineseDesc', width: 120, title: '中文描述' },
            {field: 'englishDesc', width: 120, title: '英文描述' },
            {field: 'amount', width: 100, title: '数量' ,edit:'text',
                templet: function(d){
                    let amount = d.amount?d.amount:0;
                    return Number(amount).toFixed(0)
                },totalRow: true
            },
            {field: 'unit', width: 120, title: '单位',edit:'text' },//, templet: '#unitselect'
            {field: 'price', width: 80, title: '单价' ,
                templet: function(d){
                    let price = d.price?d.price:0;
                    return Number(price)
                }
            },
            {field: 'priceSubtotal', width: 120, title: '金额小计' ,
                templet: function(d){
                    let priceSubtotal = d.priceSubtotal?d.priceSubtotal:0;
                    return Number(priceSubtotal).toFixed(2)
                },totalRow: true
            },
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称', edit: 'text'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号', edit: 'text'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码', edit: 'text'},
            {field: 'colour', width: 120, title: '颜色' },
            {field: 'grossWeight', width: 120, title: '毛重' ,edit:'text',
                templet: function(d){
                    let grossWeight = d.grossWeight?d.grossWeight:0;
                    return Number(grossWeight).toFixed(2)
                }
            },
            {field: 'grossSubtotal', width: 120, title: '毛重小计' ,
                templet: function(d){
                    let grossSubtotal = d.grossSubtotal?d.grossSubtotal:0;
                    return Number(grossSubtotal).toFixed(2)
                }
            },
            {field: 'netWeight', width: 120, title: '净重' ,edit:'text',
                templet: function(d){
                    let netWeight = d.netWeight?d.netWeight:0;
                    return Number(netWeight).toFixed(2)
                }
            },
            {field: 'netSubtotal', width: 120, title: '净重小计' ,
                templet: function(d){
                    let netSubtotal = d.netSubtotal?d.netSubtotal:0;
                    return Number(netSubtotal).toFixed(4)
                }
            },
            {field: 'volume', width: 120, title: '体积',edit:'text' ,
                templet: function(d){
                    let volume = d.volume?d.volume:0;
                    return Number(volume).toFixed(2)
                }
            },
            {field: 'trayNumber', width: 120, title: '托数' ,
                templet: function(d){
                    let trayNumber = d.trayNumber?d.trayNumber:0;
                    return Number(trayNumber).toFixed(0)
                }
            },
            {field: 'trayCapacity', width: 120, title: '每托量' ,edit:'text',
                templet: function(d){
                    let trayCapacity = d.trayCapacity?d.trayCapacity:0;
                    return Number(trayCapacity).toFixed(0)
                }
            },
            {field: 'numberOfPiece', width: 120, title: '箱数' ,
                templet: function(d){
                    let numberOfPiece = d.numberOfPiece?d.numberOfPiece:0;
                    return Number(numberOfPiece).toFixed(0)
                }
            },
            {field: 'qty', width: 120, title: '每箱数量' ,edit:'text',
                templet: function(d){
                    let qty = d.qty?d.qty:0;
                    return Number(qty).toFixed(0)
                }
            },
            {field: 'payTime', width: 120, title: '付款账期' },
            {field: 'costPrice', width: 120, title: '成本单价' ,
                templet: function(d){
                    let costPrice = d.costPrice?d.costPrice:0;
                    return Number(costPrice).toFixed(6)
                }
            },
            {field: 'costPriceSubtotal', width: 120, title: '成本小计' ,
                templet: function(d){
                    let costPriceSubtotal = d.costPriceSubtotal?d.costPriceSubtotal:0;
                    return Number(costPriceSubtotal).toFixed(2)
                }
            },
            {field: 'wholeCostPrice', width: 120, title: '成品成本' ,
                templet: function(d){
                    let wholeCostPrice = d.wholeCostPrice?d.wholeCostPrice:0;
                    return Number(wholeCostPrice).toFixed(6)
                }
            },
            {field: 'accessoryCostPrice', width: 120, title: '配件成本' ,
                templet: function(d){
                    let accessoryCostPrice = d.accessoryCostPrice?d.accessoryCostPrice:0;
                    return Number(accessoryCostPrice).toFixed(6)
                }
            },
            {field: 'supplierName', width: 120, title: '供应商' },

            {field:'outPackLength', title:'外包装长', width: 120 ,edit:'text'},
            {field:'outPackWidth', title:'外包装宽', width: 120 ,edit:'text'},
            {field:'outPackHeight', title:'外包装高', width: 120 ,edit:'text'},
            {field:'outPackSize', title:'外包装尺寸', width: 120 },
            // {field:'outPackNum', title:'外包装单位', width: 120 ,edit:'text'},
            {field:'remark', title:'备注', width: 120 ,edit:'text'},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}]],
       // page: true,
        limit:Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            if(fpzje){
                $("[data-field='priceSubtotal']").css("display", "none");
                $("[data-field='price']").css("display", "none");

            }
            if(ywbqx){
                $("[data-field='costPrice']").css("display", "none");
                $("[data-field='costPriceSubtotal']").css("display", "none");
                $("[data-field='wholeCostPrice']").css("display", "none");
                $("[data-field='accessoryCostPrice']").css("display", "none");
                $("[data-field='supplierName']").css("display", "none");

            }

            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            hoverOpenImg();//显示大图



            //外销合同号集合
            let exportContractNoList=[];
            for(let i = 0;i<res.data.length;i++){
                exportContractNoList.push(res.data[i].exportContractNo)
            }
            contractNoList=Array.from(new Set(exportContractNoList));

        }
    });


form.on("select(customscodeselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["storageproductstableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["customscode"] = data.value;
        }
    });
});
form.on("select(unitselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["storageproductstableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["unit"] = data.value;
        }
    });
});


//查询该产品的剩余数量（外销数量-出运计划数量）
function surplus_amount(flag,productId,id,exportContractNo,productNo,specNo){
    let surplusAmount=0//剩余数量
    $.ajax({
        type : 'POST',
        data: {
            wxAndBhFlag:flag,
            shipmentPlanProductId:productId,//外销或者备货的产品id
            id:id,//出运计划产品id
            exportCode:exportContractNo,
            productCode:productNo,
            specNo:specNo
        },
        url:'shipmentPlan/getSurplusAmount',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                surplusAmount=da.data;
            }
        }
    });
    return surplusAmount;
}
//form.on
//产品行编辑时触发事件
table.on('edit(storageproductstable)',function (obj) {
    var old=$(this).prev().text();//旧值

    let newValue=obj.data.amount//新值

    //判断数据类型 ,,,,,,,
    if((obj.field== "amount" || obj.field== "grossWeight"|| obj.field== "netWeight"|| obj.field== "volume" ||
        obj.field== "trayCapacity" || obj.field== "qty"|| obj.field== "outPackLength" || obj.field== "outPackWidth"
        || obj.field== "outPackHeight"  )&&!isNumber(obj.value)) {

        layer.msg('请输入数字');
        $(this).val(old);
        if(obj.field == "amount"){
            obj.update({amount:old})
        }else if (obj.field == "grossWeight"){
            obj.update({grossWeight:old})
        }else if (obj.field == "netWeight"){
            obj.update({netWeight:old})
        }else if (obj.field == "volume"){
            obj.update({volume:old})
        }else if (obj.field == "trayCapacity"){
            obj.update({trayCapacity:old})
        }else if (obj.field == "qty"){
            obj.update({qty:old})
        }else if (obj.field == "outPackLength"){
            obj.update({outPackLength:old})
        }else if (obj.field == "outPackWidth"){
            obj.update({outPackWidth:old})
        }else{
            obj.update({outPackHeight:old})
        }
        return;
    }else if((obj.field== "amount" || obj.field=="price"||obj.field=="priceSubtotal" )&& obj.value <0){
        layer.msg('数量最小为0！');
        $(this).val(old);
        if(obj.field == "amount"){
            obj.update({amount:old})
        }else if (obj.field == "price"){
            obj.update({price:old})
        }else {
            obj.update({priceSubtotal:old})
        }

        return;
    }else if (obj.field== "amount"){
        //产品id
        let id=obj.data.id;
        //代表新增
        if (!isNumber(obj.data.id)){
            id="";
        }
        //剩余数量
        let surplusAmount=surplus_amount(wxandbhflag,obj.data.productId,id,obj.data.exportContractNo,obj.data.productNo,obj.data.specNo);

        if (newValue>surplusAmount){
            layer.confirm('请注意输入的数量不能大于剩余数量!!! </br> 剩余数量为：'+surplusAmount,{icon:3,title:'提示'});
            $(this).val(old);
            if(obj.field == "amount"){
                obj.update({amount:old})
            }
            return;
        }

    }

    //以上条件判断完成，更改productList里面的数据
        for(var i=0;i<productList.length;i++){
            var row=productList[i];
            if(row.id==obj.data.id){
                row=rowBL(row);
                //数量
                    if(obj.field =="amount"){
                        row.amount=Number(obj.value).toFixed(0);
                    }
                    //每箱数量
                    if(obj.field=="qty"){
                        row.qty=Number(obj.value).toFixed(0);//数量
                    }
                    //单价
                    if(obj.field=="price"){
                        row.price=obj.value;
                    }
                    //每托量
                    if(obj.field== "trayCapacity"){
                        row.trayCapacity=obj.value;
                    }




                    row.priceSubtotal=(row.amount*row.price).toFixed(2); //priceSubtotal  金额小计     产品数量变更，  金额小计随着变化

                   row.trayNumber=Math.ceil(row.amount/row.trayCapacity).toFixed(0);//trayNumber  托数变化
                   row.numberOfPiece=Math.ceil(row.amount/row.qty).toFixed(0);//numberOfPiece 箱数变化

                    if(row.trayNumber=='Infinity'){
                        row.trayNumber=0;
                    }
                    if(row.numberOfPiece=='Infinity'){
                        row.numberOfPiece=0;
                    }

                    row.costPrice=(Number(row.wholeCostPrice)+Number(row.accessoryCostPrice)).toFixed(6);//costPrice  成本单价
                    row.costPriceSubtotal=(row.costPrice*row.amount).toFixed(2);//costPriceSubtotal   成本小计
                    //row.accessoryCostPrice=getpeijian(row.cpid,cghts,"02"); //accessoryCostPrice  配件成本
                    row.accessoryCostPrice=getpeijian2(row.cpid,row.amount);


                if(obj.field=='customerInvoiceGoodsName'){
                    row.customerInvoiceGoodsName=obj.value
                }
                if( obj.field=='customerInvoiceSpecModel' ){
                    row.customerInvoiceSpecModel=obj.value
                }
                if( obj.field=='customerMaterialsCode'){
                    row.customerMaterialsCode=obj.value
                }

                    obj.update({priceSubtotal:row.priceSubtotal,amount:row.amount,trayNumber:row.trayNumber
                                , numberOfPiece:row.numberOfPiece,costPrice:row.costPrice ,costPriceSubtotal:row.costPriceSubtotal
                                ,accessoryCostPrice:row.accessoryCostPrice,
                                customerInvoiceGoodsName:row.customerInvoiceGoodsName,
                                customerInvoiceSpecModel:row.customerInvoiceSpecModel,
                                customerMaterialsCode:row.customerMaterialsCode
                    });

                if(obj.field=="amount"){//数量改变导至发票总金额变化
                    var ia=$("input[name='invoiceAmount']")[0].value;


                    if(ia=="" ||ia =="NaN"){
                        $("input[name='invoiceAmount']")[0].value=parseFloat(row.priceSubtotal <0?0:row.priceSubtotal).toFixed(2);
                    }else{
                        //判断数量是减小还是加大
                        var zje= parseFloat(ia)+parseFloat(row.priceSubtotal)-parseFloat(old*row.price);

                       // v=parseFloat(ia)+parseFloat(row.priceSubtotal)-parseFloat(old);
                        $("input[name='invoiceAmount']")[0].value=parseFloat( zje<0?0:zje).toFixed(2);
                    }
                   // $("input[name='invoiceAmount']")[0].value=(parseFloat($("input[name='invoiceAmount']")[0].value)+getfeiyongjiner()).toFixed(2);

                }
                if(obj.field=='grossWeight'){//毛重
                    row.grossWeight=obj.value;
                    row.grossSubtotal=parseFloat(row.grossWeight*row.numberOfPiece).toFixed(2);//毛重小计
                    obj.update({grossWeight:row.grossWeight,grossSubtotal:row.grossSubtotal});
                }
                if(obj.field=='outPackLength'){//外包装长
                    row.outPackLength=obj.value;
                    row.outPackSize=row.outPackLength+"*"+row.outPackWidth+"*"+row.outPackHeight;//
                    obj.update({outPackLength:row.outPackLength,outPackSize:row.outPackSize});
                }
                if(obj.field=='outPackWidth'){//宽
                    row.outPackWidth=obj.value;
                    row.outPackSize=row.outPackLength+"*"+row.outPackWidth+"*"+row.outPackHeight;//外包装尺寸
                    obj.update({outPackWidth:row.outPackWidth,outPackSize:row.outPackSize});
                }
                if(obj.field=='outPackHeight'){//高
                    row.outPackHeight=obj.value;
                    row.outPackSize=row.outPackLength+"*"+row.outPackWidth+"*"+row.outPackHeight;//外包装尺寸
                    obj.update({outPackHeight:row.outPackHeight,outPackSize:row.outPackSize});
                }
                if( obj.field=='remark'){
                    row.remark=obj.value
                    obj.update({remark:row.remark});
                }
            }
        }
        var scr=$("[lay-id='storageproductstableid'] .layui-table-main").scrollLeft();
       table.reload('storageproductstableid', {

            data:productList
            /*,page: {
                curr: 1 //重新从第 1 页开始
            }*/

        }, 'data');
        $("[lay-id='storageproductstableid'] .layui-table-main").scrollLeft(scr);
        var pjData=[];
        for(var i=0;i<peijianList.length;i++){
            if(obj.data.cpid==peijianList[i].productId || obj.data.productId==peijianList[i].productId ){
                var arr=peijianList[i].changeList;
                //成品数量
                let proAmount=obj.data.amount
                for(var n=0;n<arr.length;n++){
                    var proportionFinishedProducts=arr[n].proportionFinishedProducts;
                    //配件比例
                    var costPriceSubtotal=arr[n].costPriceSubtotal;
                    //配件数量=成品数量*配件比例
                    if(proportionFinishedProducts !=null){
                        arr[n].amount=proAmount*proportionFinishedProducts;
                    }
                    if(costPriceSubtotal !=null && arr[n].costPrice !=null){
                        arr[n].costPriceSubtotal= parseFloat(arr[n].amount*arr[n].costPrice).toFixed(2);//配件成本小计
                    }
                    pjData.push(arr);

                }
               // pjData.push(peijianList[i].changeList);
            }
        }
        table.render({
            elem: '#productsaselect'
            ,data:pjData[0]//data2
            ,toolbar: '#productsatoolbar'
            // ,where:{id:obj.data.id} //查询的产品ID，条件
            ,cols: [[
                {checkbox: true, fixed: true}
                ,{field: 'productNo', title: '产品编码',width: 220}
                ,{field: 'specNo', title: '规格编码' }
                ,{field:'proportionFinishedProducts', title:'成品比例'}
                ,{field:'partsFinishedProducts', title:'配件比例' }
                ,{field:'amount', title:'配件数量',
                    templet: function(d){
                        let amount = d.amount?d.amount:0;
                        return Number(amount).toFixed(0)
                    }
                }
                ,{field: 'costPrice', width: 120, title: '成本单价'  ,
                    templet: function(d){
                        let costPrice = d.costPrice?d.costPrice:0;
                        return Number(costPrice).toFixed(6)
                    }
                }
                ,{field: 'costPriceSubtotal', width: 120, title: '成本小计'  ,
                    templet: function(d){
                        let costPriceSubtotal = d.costPriceSubtotal?d.costPriceSubtotal:0;
                        return Number(costPriceSubtotal).toFixed(2)
                    }
                }
                ,{field: 'purchaseNo', width: 120, title: '采购单号' }
                ,{field: 'supplierName', width: 120, title: '供应商' }
                ,{field:'chineseName', title:'中文名称' }
                ,{field:'englishName', title:'英文名称' }
                ,{field:'grossWeight', title:'毛重' , edit:'text' ,
                    templet: function(d){
                        let grossWeight = d.grossWeight?d.grossWeight:0;
                        return Number(grossWeight).toFixed(2)
                    }
                }
                ,{field:'netWeight', title:'净重' , edit:'text' ,
                    templet: function(d){
                        let netWeight = d.netWeight?d.netWeight:0;
                        return Number(netWeight).toFixed(2)
                    }
                }
                ,{field:'volume', title:'体积' , edit:'text' ,
                    templet: function(d){
                        let volume = d.volume?d.volume:0;
                        return Number(volume).toFixed(2)
                    }
                }
                ,{fixed: 'right', width:150, align:'center', toolbar: '#productsaup', title:'操作'}
            ]]
            ,id: 'productsatableid'
            //,page: false
            ,limit:Number.MAX_VALUE
            ,height:300
            , done: function (res, curr, count) {

                if(ywbqx){
                    $("[data-field='costPrice']").css("display", "none");
                    $("[data-field='costPriceSubtotal']").css("display", "none");
                    $("[data-field='supplierName']").css("display", "none");

                }


            }
        });


    $("[data-field='"+obj.field+"'] input").blur()

});
//遍历行中每一个值
function rowBL(obj){
    Reflect.ownKeys(obj).forEach(function(key){
       if(obj[key]==undefined || obj[key]==null ){
           obj[key]="";
       }
       if(obj[key]==NaN){
           obj[key]="0";
       }
       // console.log(key,obj[key]);

    });
    return obj;
}
    //监听行单击事件
    table.on('row(storageproductstable)', function(obj){
        $("#hidden").show();

        var pjData=[];
        for(var i=0;i<peijianList.length;i++){
            if(obj.data.productId==peijianList[i].productId){
                pjData.push(peijianList[i].changeList);
            }
        }
        table.render({
            elem: '#productsaselect'
            ,data:pjData.length==0?pjData:pjData[0]//pjData[0]//data2
            ,toolbar: '#productsatoolbar'

            ,cols: [[
                {checkbox: true, fixed: true}
                ,{field: 'productNo', title: '产品编码',width: 220}
                ,{field: 'specNo', title: '规格编码' }
                ,{field:'proportionFinishedProducts', title:'成品比例'}
                ,{field:'partsFinishedProducts', title:'配件比例' }
                ,{field:'amount', title:'配件数量' }
                ,{field: 'costPrice', width: 120, title: '成本单价' ,
                    templet: function(d){
                        let costPrice = d.costPrice?d.costPrice:0;
                        return Number(costPrice).toFixed(6)
                    }}
                ,{field: 'costPriceSubtotal', width: 120, title: '成本小计' ,
                    templet: function(d){
                        let costPriceSubtotal = d.costPriceSubtotal?d.costPriceSubtotal:0;
                        return Number(costPriceSubtotal).toFixed(2)
                    }}
                ,{field: 'purchaseNo', width: 120, title: '采购单号' }
                ,{field: 'supplierName', width: 120, title: '供应商' }
                ,{field:'chineseName', title:'中文名称' }
                ,{field:'englishName', title:'英文名称' }
                ,{field:'grossWeight', title:'毛重' , edit:'text',
                    templet: function(d){
                        let grossWeight = d.grossWeight?d.grossWeight:0;
                        return Number(grossWeight).toFixed(2)
                    }}
                ,{field:'netWeight', title:'净重' , edit:'text',
                    templet: function(d){
                        let netWeight = d.netWeight?d.netWeight:0;
                        return Number(netWeight).toFixed(2)
                    }}
                ,{field:'volume', title:'体积' , edit:'text',
                    templet: function(d){
                        let volume = d.volume?d.volume:0;
                        return Number(volume).toFixed(2)
                    }}
                ,{fixed: 'right', width:150, align:'center', toolbar: '#productsaup', title:'操作'}
            ]]
            ,id: 'productsatableid'
           // ,page: false
            ,limit:Number.MAX_VALUE
            ,height:300
            , done: function (res, curr, count) {

                if(ywbqx){
                    $("[data-field='costPrice']").css("display", "none");
                    $("[data-field='costPriceSubtotal']").css("display", "none");
                    $("[data-field='supplierName']").css("display", "none");

                }


            }
        });
    });
table.on('edit(productsatable)',function (obj) {
    var old=$(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if((obj.field== "grossWeight" || obj.field== "netWeight"|| obj.field== "volume" )&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
});
//修改中行删除
table.on('tool(storageproductstable)', function (obj) {
    if (obj.event === 'del') {
        layer.confirm('真的删除行么', function (index) {
            var ia=$("input[name='invoiceAmount']")[0].value;
            if(ia=="" || ia =="NaN"){
                ia=0;
            }

            $("input[name='invoiceAmount']")[0].value= (parseFloat(ia)-parseFloat(obj.data.priceSubtotal==undefined?"0":obj.data.priceSubtotal)).toFixed(2);

            for(var i=0;i< productList.length; i++){
                if(productList[i].productId==obj.data.productId){
                    obj.del();
                    productList.splice(i,1);
                    setXSHTH(obj.data.exportContractNo,0);
                    //同步配件删除
                    for(var i2=0;i2< peijianList.length;i2++){
                        if(peijianList[i2].productId==obj.data.productId){
                            var changeList= peijianList[i2].changeList;
                            for(var n=0;n<changeList.length;n++){
                                if(changeList[n].productId==obj.data.productId){
                                    peijianList.splice(i2,1);

                                }
                            }
                        }
                    }
                    //刷新部件列表
                    var cbList = table.cache["productsatableid"];
                    for(var i2 = 0;i2< cbList.length;i2++){
                        //delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i2]) != undefined&&obj.data.productId == cbList[i2].productId) {
                                cbList.splice(i2, 1);
                            }
                       // })
                    }
                    table.reload("productsatableid", {
                        data: cbList,limit:cbList.length
                    });
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
        });
    }
});
//产品导入
table.on('toolbar(storageproductstable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'importexport'://导入外销
            if(wxandbhflag=="b"){
                layer.msg("已导入备货，不可再导入外销！");
                break;
            }
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']":['75%', '75%'],
                content: 'views/jsp/ExportBusiness/tpl/importexport.jsp'
            });
            break;
        case 'importstockup'://导入备货
            if(wxandbhflag=="w"){
                layer.msg("已导入外销，不可再导入备货！");
                break;
            }
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']":['75%', '75%'],
                content: 'views/jsp/ExportBusiness/tpl/importstockup.jsp'
            });
            break;
        case 'new':
            var oldData = table.cache["storageproductstableid"];
            var data1={
                "id":oldData.length+1,
                warehousename:"",
                number:"",unit:"1",
                unitprice:"",
                amountsubtotal:"",
                costprice:"",
                costsubtotal:"",
                productcode:""
            };
            var sss = oldData.concat(data1);
            table.reload('storageproductstableid',{data : sss,limit:sss.length});
            getlxandlevel();
            break;
        case 'del':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
               delList.push(n.id);
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["storageproductstableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != undefined&&item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    var tmpList=productList;
                    for(var i=0;i<tmpList.length ; i++){
                        for(var n=0;n<delList.length ;n++){
                            if(tmpList[i].id==delList[n]){
                                let pid=productList[i].productId;

                                let contractNoStr=setXSHTH(productList[i].exportContractNo,0);

                                //同步删除费用
                                let costList = table.cache["costtableid"];
                                for (let c in costList) {
                                    if (contractNoStr.indexOf(costList[c].contractNo)===-1){
                                        costList.splice(c,1);
                                    }
                                }
                                table.reload("costtableid", {
                                    data: costList,limit:costList.length
                                });

                                //同步配件删除
                                for(var i2=0;i2<peijianList.length ;i2++){
                                    if(peijianList[i2].productId==pid){
                                        var changeList= peijianList[i2].changeList;
                                        for(var n2=0;n2<changeList.length ;n2++){
                                            if(changeList[n2].productId==pid){
                                                peijianList.splice(i2,1);
                                            }
                                        }
                                    }
                                }
                                //刷新配件列表
                                let partList = table.cache["productsatableid"];
                                if (partList){
                                    for(var i2 =0;i2< partList.length ;i2++){
                                        //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                        if (typeof (partList[i2]) != undefined && pid == partList[i2].productId) {
                                            partList.splice(i2, 1);
                                        }
                                    }
                                    table.reload("productsatableid", {
                                        data: partList,limit:partList.length
                                    });
                                }
                                //更新发票总额
                                let invoiceAmount=new BigNumber($("input[name='invoiceAmount']")[0].value);
                                let priceSubtotal=new BigNumber(productList[i].priceSubtotal);
                                $("input[name='invoiceAmount']")[0].value=invoiceAmount.minus(priceSubtotal).toFixed(2);

                                //删除成品列表的数组
                                productList.splice(i,1);
                            }
                        }
                    }
                    //刷新成品列表
                    table.reload("storageproductstableid", {
                        data: cbList,limit:cbList.length
                    });
                    layer.msg('删除成功');


                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }


    table.on('toolbar(productsatable)', function(obj){

        var checkStatus = table.checkStatus(obj.config.id);
        var data = checkStatus.data;
        switch(obj.event){
            case 'new':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']":['75%', '75%'],
                    content: 'views/jsp/ExportBusiness/tpl/productlibraryimport.jsp?tableid=productsatableid'
                });
                break;
            case 'delet':
                var data=checkStatus.data,delList=[];
                data.forEach(function(n,i){
                    delList.push(n.id);
                });
                if(delList!=''){
                    layer.confirm('确定删除所选项吗？',function (index) {
                        var cbList = table.cache["productsatableid"];
                        for(var i = 0;i<cbList.length;i++){
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != undefined&&item == cbList[i].id) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("productsatableid", {
                            data: cbList,limit:cbList.length
                        });
                        layer.msg('删除成功');
                    })
                }else{
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });
    table.on('tool(productsatable)', function(obj){

        var data = obj.data;
        if(obj.event === 'productsade') {
            layer.confirm('真的删除行么', function (index) {


                   for(var i=0;i<peijianList.length;i++){

                       if(peijianList[i].productId=data.productId){
                           var changeList= peijianList[i].changeList;
                           for(var n=0;n<changeList.length;n++){
                               if(changeList[n].productId==obj.data.productId){
                                  // if( delproduct(obj.data.id,"b")){
                                      obj.del();

                                       peijianList.splice(i,1);
                                       layer.msg('删除成功');
                                   /*}else{
                                       layer.msg('删除失败');
                                   }*/
                               }
                           }
                       }
                   }



                layer.close(index);
            });
        }
    });

//---费用
    table.render({
        elem: '#cost'
        , data: feiyong
        , toolbar: '#costtoolbar'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'id', title: 'Id',hide:true}
            , {field: 'contractId', title: '外销费用id',hide:true}
            , {field: 'costType',title: '费用类型', templet:'#costtypeselects'}
            , {field: 'costMoney', title: '金额',event:'amount',edit:'number'}
            , {field: 'contractNo', title: '销售合同号', templet:'#contractNoSelect'}
            , {field: 'costDesc', title: '备注说明',edit:'text'}
        ]]
        , id: 'costtableid'
        , height: 380
        , page: true
        ,done:function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')

            if (id != ""){
                for (let j in costTypeListAll) {
                    $(".costTypeClass").append(new Option(costTypeListAll[j].name,costTypeListAll[j].code));
                }
            }else {
                for (let j in costTypeList) {
                    $(".costTypeClass").append(new Option(costTypeList[j].name,costTypeList[j].code));
                }
            }

            for (let j in contractNoList) {
                $(".contractNoClass").append(new Option(contractNoList[j],contractNoList[j]));
            }

            for (var i = 0; i < res.data.length; i++) {
                $("#costType_" + res.data[i].contractId).val(res.data[i].costType);
                $("#contractNo_" + res.data[i].contractId).val(res.data[i].contractNo);
            }

            form.render('select');
        }
    });

table.on('edit(costtable)',function (obj) {
    var old=$(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if((obj.field== "costMoney")&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);

        return;
    }
    if(obj.field=="costMoney"){
        let invoiceAmount=new BigNumber($("input[name='invoiceAmount']")[0].value);
        let newValue=new BigNumber(obj.value);
        let oldValue=new BigNumber(old);
        $("input[name='invoiceAmount']")[0].value=invoiceAmount.plus(newValue).minus(oldValue).toFixed(2);
    }

});

//监听货柜型号下拉框
form.on("select(containerTypeCode)", function(data){
    if(data.value === ""){
        $('#containerType').val("");
        return;
    }
    for(let i in containerModel){
        if(data.value == containerModel[i].code){
            $('#containerType').val(containerModel[i].name);
        }
    }
});

form.on("select(costType_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["costtableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["costType"] = data.value;
        }
    });
});

form.on("select(contractNo_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["costtableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["contractNo"] = data.value;
        }
    });
});

//费用工具按钮
table.on('toolbar(costtable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){
        case 'new':
            let oldData = table.cache["costtableid"];
            let data1={
                contractId:GenNonDuplicateID(3) + (oldData.length + 1),
                costType:"",
                costMoney:0,
                costDesc:""
            };
            oldData.push(data1)
           table.reload('costtableid',{data : oldData});
            break;
        case 'del':
            let data=checkStatus.data,
                delList=[];
            data.forEach(function(n,i){
                delList.push(n.contractId);
            });
            if(delList.length>0){
                layer.confirm('确定删除所选项吗？',function (index) {
                    let costList = table.cache["costtableid"];
                    for(var i = 0;i<costList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (costList[i]) != "undefined" && item == costList[i].contractId) {
                                let invoiceAmount=new BigNumber($("input[name='invoiceAmount']")[0].value);
                                let costMoney=new BigNumber(costList[i].costMoney);
                                $("input[name='invoiceAmount']")[0].value=invoiceAmount.minus(costMoney).toFixed(2);
                                costList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("costtableid", {
                        data: costList,
                    });
                    feiyong=costList;
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});


//---附件
//[{"fileName":"test","fileUploadTime":"2021-01-02"}];
    table.render({
        elem: '#attachment'
        , data: fujian
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true,event: "fileName"}
            , {field: 'id', title: 'Id' ,hide:true}
            , {field: 'fileUploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        ,done:function (res, curr, count) {
           // $("[data-field='id']").css("display", "none");
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , done: function (res, index, upload) {

            if(res.status==200){//上传成功
                let data = res.data;
                for(let i in data){
                    let obj = {};
                    obj["fileName"] = res.data[i].originalFileName;
                    obj["fileUrl"] = res.data[i].ftpPath+"/"+res.data[i].fileName;
                    obj["fileUploadTime"] = timestampToTime(Date.now());
                    obj["id"] = GenNonDuplicateID(3);
                    fujian.push(obj);
                }

                table.reload('attachmenttableid',{data : fujian});

                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                      //  table.reload('attachmenttableid', {}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {

        var data = obj.data;
        if (obj.event === 'download') { //下载
            downFileLoadNew(data.fileName,data.fileUrl);
          //  downFileLoad(obj.data.fileUrl);
          /*  var a = document.createElement('a');
            var event = new MouseEvent('click');
            a.download = data.filename;
            a.href = data.url;
            a.dispatchEvent(event)*/
        } else if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                //需要删除的ID：data.id
                obj.del();
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                var temfj=[];
                for(var i=0;i<fujian.length;i++){
                    var tem=fujian[i];
                    if(tem.id != data.id){
                        temfj.push(tem);
                    }
                }
                fujian=temfj;
                //table.reload('attachmenttableid', {}); //ajax删除成功之后刷新表格
            });
        }else if(obj.event === 'fileName'){//点击名称，在线预览
            onLineFile(obj.data.fileUrl);
        }
    });

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        //, data: data2
        ,url:"shipmentPlan/getLogByPage"
        ,where: {
            "shipmentPlanId": id
        }
        ,method:"get"
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'opname', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });


function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}
//获取费用小计
function  getcostSum() {
//费用
    var obj=0;
    var cost=table.cache["costtableid"];
    var cList=[];
    for(var i=0;i<cost.length;i++){
        if(cost[i].length !=0){

            obj+=cost[i].costMoney;
        }
    }
    return obj;
}

//保存出运计划
function  save(data) {
    let msgFlag="true";
    data.flag=wxandbhflag;
    data.customerName=impcustomerName
    data.customerCode=impcustomerCode;
   var pl=[];
   // pl=productList;
    for(var i=0; i<peijianList.length;i++){
        var changeList=peijianList[i].changeList;
        for(var n=0;n<changeList.length;n++){
            pl.push(changeList[n]);
        }

    }
    for(var i=0;i<productList.length;i++){
        if(productList[i].id==null){
            pl.push(productList[i])
        }else{
            if((""+productList[i].id).startsWith("ls")){
                productList[i].id=null;
            }
            pl.push(productList[i])
        }
    }
    data.productList=pl;
    //费用
    var cost=table.cache["costtableid"];
    var cList=[];
    for(var i=0;i<cost.length;i++){
        if(cost[i].length !=0){
            if (!cost[i].contractNo){
                return "费用列表中销售合同号不能为空";
            }
            var obj={};
            obj.costDesc=cost[i].costDesc;
            obj.costMoney=cost[i].costMoney;
            obj.costType=cost[i].costType;
            obj.contractNo=cost[i].contractNo;
            obj.contractId=cost[i].contractId;
            cList.push(obj);
        }
    }
   data.costList=cList;
    //附件
    var fj=[];
    for(var i=0;i<fujian.length;i++){
        var obj={};
        obj.fileName=fujian[i].fileName;
        obj.fileUrl=fujian[i].fileUrl;
       // obj.fileUploadTime=fujian[i].fileUploadTime;
        obj.fileType=fujian[i].type;
        obj.fileSize=fujian[i].size;
        fj.push(obj);
    }
//此处有问题，待调试
    data.fileList=fj;

//保存主信息
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data: JSON.stringify(data),
        url:'shipmentPlan/insert',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                setTimeout(function () {
                    //保存成功则刷新提交过来的界面 并关闭此页面
                    parent.detab("views/jsp/ExportBusiness/shipmentplan.jsp");
                    parent.intab("views/jsp/ExportBusiness/shipmentplan.jsp","出运计划")
                    parent.detab("views/jsp/ExportBusiness/tpl/newupshipmentplan.jsp","新增出运计划");
                    parent.detab("views/jsp/ExportBusiness/tpl/newupshipmentplan.jsp"+(id==''?'':'?id='+id));
                },1000);
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });

    return msgFlag;
}

//获取字典
function getdictionary(dl,xl) {
    var obj=[];
    $.ajax({
        type : 'POST',
        data: {"type":dl,"lx":xl},
        url:'dictionary2/getValues',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj=da.data;
            }
        }
    });
    return obj;
}
//获取下拉列表值
function getlxandlevel() {
    var curry=getdictionary(5,14);//币种
    var termspay=getdictionary(5,18);//收款方式
    var priceterm=getdictionary(5,16);//价格术语
    var business=getdictionary(6,20);//业务模式
    var destin = getdictionary(6,29) //目的地
    var places = getdictionary(6,31); //起运地
   // var bankValue = getdictionary(6,32); //银行
    var unit = getdictionary(6,42); //单位
    var costtype = getdictionary(5,19);  //费用类型
    var declarecompany=getdictionary(6,48);//报关抬头
    var transmode=getdictionary(2,5);//运输方式
    var stock=getdictionary(4,11);//仓库

    var currency=$("select[name='currency']");//币种
    var priceterms = $("select[name='priceTerm']"); //价格术语
    var termspayment = $("select[name='paymentTerm']"); //收款类型
    var businessmode = $("select[name='businessMode']"); //业务模式
    var place = $("select[name='startPlace']"); //起运地
    var destination = $("select[name='endPlace']"); //目的地
   // var bank = $("select[name='bankCode']"); //银行
    var declarecompanystr=$("select[name='declareCompany']");//报关抬头
    var transmodestr=$("select[name='transMode']");//运输方式
    var targetcountrystr=$("select[name='targetCountry']");//运抵国家
    var stockstr=$("select[name='stock']");//仓库
    var unitselect = $("select[name='unitselect']"); //单位

    currency.append(getoption(curry)); //币种
    priceterms.append(getoption(priceterm)); //价格术语
    termspayment.append(getoption(termspay)); //付款方式
    businessmode.append(getoption(business)); //业务模式
    place.append(getoption(places)); //起运地
    destination.append(getoption(destin)); //目的地
   // bank.append(getoption(bankValue)); //银行
    // var bank = $("select[name='bankCode']"); //银行
    unitselect.append(getoption(unit)); //单位
    declarecompanystr.append(getoption(declarecompany));//报关抬头
    transmodestr.append(getoption(transmode));//运输方式
    targetcountrystr.append(getoption(destin));//运抵国家
    stockstr.append(getoption(stock));//运抵国家

    form.render();

}



//获取用户
function getUser() {
    var obj=[];
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        url:'shipmentPlan/getAllUser',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                for(var i=0;i<da.data.length;i++){
                    var data={};
                    data.code=da.data[i].code;
                    data.name=da.data[i].name;
                    obj.push(data);
                }
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}


//获取签约公司
function getCompany() {
    var obj=[];
    $.ajax({
        type : 'GET',
        url:'shipmentPlan/getCompany',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){

                for(var i=0;i<da.data.length;i++){
                    var data={};
                    data.code=da.data[i].code;
                    data.name=da.data[i].name;
                    obj.push(data);
                }
            }
        }
    });
    return obj;
}

function setPullMenu(){
    var company = getCompany();   //签约公司
  //  var customer = getCustomer();   //客户名称
   var opname=getUser();//业务员
    salesmanList=getUser();//业务员

    var companyid = $("select[name='companyCode']"); //签约公司
    var customername = $("select[name='customerCode']"); //客户名称
    var opnamestr=$("select[name='salesmanCode']"); //业务员
    var containerTypeCode=$("select[name='containerTypeCode']"); //货柜型号

    companyid.append(getoption(company));
  //  customername.append(getoption(customer));
    opnamestr.append(getoption(opname));
    form.render();
}
function  getoption(objs) {
    var stoptions="";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
    }
    return stoptions;
}

//判断当前登录用户是否为 营销部门的总监 角色
function is_marketing_director() {
    $.ajax({
        url:'customer/isMarketingDirector',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                isMarketingDirector=da.data;
            }
        }
    });
}
//判断当前登录用户是否为 营销部门的总监 管理角色
function is_marketing_director_msn() {
    $.ajax({
        url:'shipmentPlan/isMarketingDirectorMsn',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                isMarketingDirectorMsn=da.data;
            }
        }
    });
}
function queryByid(da) {
    $.ajax({
        type : 'GET',
        data:{"id":da},
        url:'shipmentPlan/selectByKey',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                initData(da.data);
            }
        }
    });
}
function  initData(data) {
    form.val("editor-form", {
        "id": data.id,
        "customerCode": data.customerName,//客户名称
        "contactPerson": data.contactPerson,//联系人
        "shipmentNo": data.shipmentNo,//计划编号
        "shipmentDate": data.shipmentDate,//出运日期
        "currency": data.currency,//币种
        "usdRate": data.usdRate,//美元汇率
        "rmbRate": data.rmbRate,//人民币汇率
        "startPlace": data.startPlace,//起运地
        "endPlace": data.endPlace,//目的地
        "targetCountry": data.targetCountry,//运抵国家
        "transhipment": data.transhipment,//转船运输
        "transMode": data.transMode,//运输方式
        "paymentTerm": data.paymentTerm,//收款类型
        "priceTerm": data.priceTerm,//价格术语
        "invoiceAmount": data.invoiceAmount,//发票总额
        "makeTime": data.makeTime,//制单日期
        "salesContractNo": data.salesContractNo,//销售合同号
        "customerContractNo": data.customerContractNo,//客户合同号
        "salesmanCode": data.salesmanCode,//业务员
        "salesmanName": data.salesmanName,//业务员
        "businessMode": data.businessMode,//业务模式
        "proFinishDate": data.proFinishDate,//货好日期
        "brand": data.brand,//品牌
        "stock": data.stock,//仓库
        "boxType": data.boxType,//箱型
        "payDay": data.payDay,//客户账期
        "declareCompany": data.declareCompany,//报关抬头
        "companyCode": data.companyCode,//签约公司
        "bankCode": data.bankCode,//银行
        "executorCode":data.executorCode,//操作员
        "executorName":data.executorName,
        "customerLevelName":data.customerLevelName,//客户等级名称
        "customerLevelCode":data.customerLevelCode,//客户等级编码
        "containerNum":data.containerNum,//货柜数量
        "containerTypeCode":data.containerTypeCode,//货柜型号编码
        "containerType":data.containerType,//货柜型号
        "whetherCreditGuarantee":data.whetherCreditGuarantee,//是否走信保订单(0:否 1:是)
        "creditGuaranteeAmount":data.creditGuaranteeAmount//信保订单金额USD
    })
    businessMode=data.businessMode;//业务模式
    parentCustomerCode=data.customerCode;//客户编码
    parentCurrencyCode=data.currency;//币种编码
    parentPriceTermsCode=data.priceTerm;//价格术语编码

    wxandbhflag=data.flag;
   impcustomerCode=data.customerCode;
   impcustomerName=data.customerName;

    getBank(data.companyCode);
    form.render();
}
//根据签约公司编码获取银行
function getBank(data) {
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        url:'shipmentPlan/getBank',
        data:{"companyCode":data},
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                var data=da.data;
                var bankValue=[];
                for(var i=0;i<data.length;i++){
                    var obj={};
                    obj.code=data[i].bankcode;
                    obj.name=data[i].bankname;
                    bankValue.push(obj);
                }
                // productList=da.data;
                // fujian.push(da.data);
               // fujian=da.data;
                if(bankValue.length > 0){
                    var bank = $("select[name='bankCode']"); //银行
                      bank.empty();
                    bank.append(getoption(bankValue)); //银行
                    form.render();
                }

            }
        },
        error: function(data) {
            // layer.msg("获取失败!"); 日志
        }
    });
}
//附件
function getfujian() {
    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        url:'shipmentPlan/selectFileBySpId',
        data:{"shipmentPlanId":id},
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                // productList=da.data;
               // fujian.push(da.data);
                fujian=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!"); 日志
        }
    });
    table.reload('attachmenttableid',{data : fujian});
}
//费用 获取数据
function getfeiyong() {
    $.ajax({
        type : 'GET',
        url:'shipmentPlan/selectCostBySpId',
        data:{"shipmentPlanId":id},
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                feiyong=da.data;
            }
        }
    });
    table.reload('costtableid', {
        data:feiyong
        ,page: {
            curr: 1 //重新从第 1 页开始
        }

    }, 'data');

}
//产品获取数据
function  getProdcuInfo() {

    $.ajax({
        type : 'GET',
        //  url : 'resource/getTree',
        url:'shipmentPlan/selectProductByShipmentPlanId',
        data:{"spId":id},
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
               // productList=da.data;
                getProductList(da.data);
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
}
//回显时拼装产品列表与部件列表
function getProductList(data) {
    var changeList=[];
   for(var i=0;i<data.length;i++){
       //data[i].supplierName=data[i].supplierCode;
       if(data[i].type=="1") {//产品
           productList.push(data[i]);
           setXSHTH(data[i].exportContractNo,1);
       }else{//部件
           changeList.push(data[i]);
       }
   }
   //遍历changeList，组装部件列表
    for(var i=0;i<changeList.length;i++){
        var productId=changeList[i].productId;
         getPeijianList(productId,changeList[i]);
    }


}
//组装部件列表
function getPeijianList(productId,pj) {
    var tf=false;
   for(var i=0;i<peijianList.length;i++){
       if(productId == peijianList[i].productId){
           tf=true;
           (peijianList[i].changeList).push(pj);
           return ;
       }
   }
   if(peijianList.length==0 || tf){
       var changeList=[];
       changeList.push(pj);
       var jsons = {"productId":productId,"changeList":changeList};
       peijianList.push(jsons)
   }else{
       for(var i=0;i<peijianList.length;i++){
           if(productId == peijianList[i].productId){
               (peijianList[i].changeList).push(pj);
               return;
           }
       }
       if(!tf){
           var changeList=[];
           changeList.push(pj);
           var jsons = {"productId":productId,"changeList":changeList};
           peijianList.push(jsons)
       }
   }

}
//##########################未修改#################################################
//导入外销、备货时可选多合同，即多对多

//产品导入后刷新表格，外销
function cyjhresh(productListin,waixiaohetong){//外销产品列有，外销合同
    productList=[];//产品列表数据源
    peijianList=[];//配件列表数据源
    getProdcuInfo();//如果是修改，导入表中的数据

    var exportContractNo=waixiaohetong.billNo;//外销合同号
    var pcodandgcode=[];//产品编码+规格编码
    var productListFrom=[];//导入外销的产品
     var producListTem=[];//临时缓存
    //从外销合同中取相关数据
         //业务模式
         var businessModelName=waixiaohetong.businessModelName;
   //通过 销售合同号获取采购合同产品、配件
    var cghts=getCG(exportContractNo );//getCG(exportContractNo,pcodandgcode);
    peijianList=cghts;
    //根据产品编码过虑
    for(var i=0;i<cghts.length;i++){
        var pn=cghts[i].productNo;//采购中的产品编码
        for(var n=0;n<productListin.length;n++){
            var pl=productListin[n].productCode;///外销中的产品编码
            if(pn==pl){
                producListTem.push(cghts[i]);
                break;
            }
        }
    }
   // peijianList=cghts;//包含产品与配件，用采购类型来区分
    cghts=producListTem;

    //取出采购产品、外销产品，拼装出运计划产品
    for(var i=0;i<cghts.length;i++){
        if("1"==cghts[i].purchaseType){//成品；2：配件
            var obj={};
            /*obj.productNo=cghts[i].productNo;//产品编码
            obj.specNo=cghts[i].specNo;//规格编码*/
            if(businessModelName.indexOf("正常") != -1){
                obj.purchaseNo=cghts[i].purchaseOrderNo;//采购单号
                obj.amount=cghts[i].amount;//采购中数量
            }else{
                obj.purchaseNo="";//采购单号为空
            }
            //毛重
            obj.grossWeight=cghts[i].grossWeight;
            //净重
            obj.netWeight=cghts[i].netWeight;
            //体积
            obj.volume=cghts[i].volume;
            // 托数
            obj.trayNumber=cghts[i].trayNumber;
            // 每托量
            obj.trayCapacity=cghts[i].trayCapacity;
            // 件数
            obj.numberOfPiece=cghts[i].numberOfPiece;
            // 每件数量
            obj.qty=cghts[i].qty;
            //付款账期
            obj.payTime=cghts[i].payTime;
            //成品成本
            obj.wholeCostPrice=cghts[i].price;
            //供应商
            obj.supplierCode=cghts[i].supplierCode;//编码
            obj.supplierName=cghts[i].supplierName;//名称
            //obj.purchaseId=cghts[i].purchaseId;//采购尖
            //开始比对外销
            var tf=0;
            for(var n=0;n<productListin.length;n++){
                if(cghts[i].productNo+cghts[i].specNo==productListin[n].productCode+productListin[n].specificationCode){
                    tf=1;
                    obj.productNo=productListin[n].productCode;//产品编码
                    obj.specNo=productListin[n].specificationCode;//规格编码
                    obj.normExplain=productListin[n].specificationExplanation;//规格说明
                    obj.customerContractNo= productListin[n].clientProductNo;//客户货号
                    obj.chineseName= productListin[n].productCname;//', width: 120, title: '中文名称',edit:'text'},
                    obj.englishName= productListin[n].productEname;//', width: 120, title: '英文名称',edit:'text'},
                    obj.chineseDesc= productListin[n].productCdesc;//', width: 120, title: '中文描述',edit:'text'},
                    obj.englishDesc= productListin[n].productEdesc;//', width: 120, title: '英文描述',edit:'text'},
                    obj.colour= productListin[n].color;//', width: 120, title: '颜色',edit:'text'},
                    obj.exportContractNo= exportContractNo;//productListin[n].billNO;//', width: 120, title: '外销合同号',edit:'text'},
                    obj.outPackLength= productListin[n].outerPackingLong;//', title:'外包装长', width: 120, edit: 'text'},
                    obj.outPackWidth= productListin[n].outerPackingWide;//', title:'外包装宽', width: 120, edit: 'text'},
                    obj.outPackHeight= productListin[n].outerPackingHeight;//', title:'外包装高', width: 120, edit: 'text'},
                    if(businessModelName.indexOf("正常") == -1){
                        obj.amount=productListin[n].productNum;//数量,外销中数量
                        obj.accessoryCostPrice=0;//配件成本
                    }else{//正常模式
                        obj.amount= cghts[i].amount;//采购中数量
                      //  obj.accessoryCostPrice=peijiancb(exportContractNo,obj.productNo,obj.specNo,businessModelName,productListin[n].id,waixiaohetong.id);//配件成本
                    }
                    obj.unit= productListin[n].productUnitName;//', width: 120, title: '单位', templet: '#unitselect'},
                    obj.price= productListin[n].unitPrice;//', width: 80, title: '单价',edit:'text'},
                    obj.priceSubtotal=obj.price*obj.amount;//金额小计
                    obj.grossSubtotal=obj.grossWeight*obj.numberOfPiece;//毛重小计
                    obj.netSubtotal=obj.netWeight*obj.numberOfPiece;//净重小计
                    obj.trayNumber=obj.amount/obj.trayCapacity;//托数
                    obj.numberOfPiece=obj.amount/obj.qty;//件数
                    obj.outPackSize=obj.outPackLength*obj.outPackWidth*obj.outPackHeight;//外包装尺寸
                    obj.costPrice=obj.wholeCostPrice+obj.accessoryCostPrice;//成品单价
                    obj.costPriceSubtotal=obj.costPrice*obj.amount;//成本小计


                    break;
                }
            }
            if(tf==0){//如果采购合同中的产品与外销中选择的产品不匹配，不处理
                continue;
            }
            productList.push(obj);

        }



    }
    //取出产品配件  peijianList

    //setProduct(productList);

    layer.msg("OK ");
    table.reload('storageproductstableid', {

        data:productList,limit:productList.length
        /*,page: {
            curr: 1 //重新从第 1 页开始
        }*/

    });
}

/**
 * 根据外销合同号获取采购合同
 */
function getCG(exportContractNo) {
    var cght=[];
    $.ajax({
        type : 'GET'
        //  url : 'resource/getTree',salesContractNo
        ,data:{"salesContractNo":exportContractNo },
        url:'shipmentPlan/selectCaiGuoByWaiXiao',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
               cght=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return cght;
}

//通过 外销合同号、产品编码、规格编码获取配件成本
function peijiancb(salesContractNo,productNo,specNo,businessModelName,wxid,wxhtid) {
//正常业务，有采购单号
    if(businessModelName.indexOf("正常") != -1){
        var pjcb=0;//配件成本
        for(var i=0;i<peijianList.length;i++){
            if(salesContractNo==peijianList[i].salesContractNo && peijianList[i].productNo==productNo
                && peijianList[i].specNo==specNo &&peijianList[i].purchaseType=="2"){
                pjcb+=peijianList[i].costPrice;
            }
        }
        var bj=[];
        var wxcp=getwxbj(wxid);//外销产品部件
        for(var i=0;i<peijianList.length;i++){
            if(peijianList[i].purchaseType=="1"){
                continue;
            }
            var obj={};
            obj.productNo=productNo;//产品编码
            obj.specNo=specNo;//规格编码
            for(var n=0;n<wxcp.length;n++){
                if(productNo == wxcp[n].partsCode){//采购部件中的产品编码与外销中的部件编码
                    obj.proportionFinishedProducts=wxcp[i].proportionFinishedProducts;//成品比例
                    obj.partsFinishedProducts=wxcp[i].partsFinishedProducts;//配件比例
                }
            }
            obj.amount=peijianList[i].amount;//配件数量
            obj.costPrice=peijianList[i].costPrice;//成本单价
            obj.costPriceSubtotal=peijianList[i].costPriceSubtotal;//成本小计
            obj.purchaseNo=peijianList[i].purchaseNo;//采购单号
            obj.supplierName=peijianList[i].supplierName;//供应商
            obj.chineseDesc=peijianList[i].productCname;//中文名称
            obj.englishDesc=peijianList[i].productEname//英文名称
            obj.grossWeight=peijianList[i].grossWeight;//毛重
            obj.netWeight=peijianList[i].netWeight;//净重
            obj.volume=peijianList[i].volume;//体积
            bj.push(obj);

        }
        peijianList=bj;
        return pjcb;
    }else{//配件从外销中取
        peijianList=[];
        var wxpj=[];
        $.ajax({
            type : 'GET'
            //  url : 'resource/getTree',salesContractNo
            ,data:{"id":wxid },//外销产品id
            url:'exportContract/import/getContractProductPartsById',
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    wxpj =da.data;
                }
            },
            error: function(data) {
                //layer.msg("获取失败!");
            }
        });
        for(var i=0;i<wxpj.length;i++){
            var obj={};
            obj.productNo=productNo;//产品编码
            obj.specNo=specNo;//规格编码
            obj.proportionFinishedProducts=wxpj[i].proportionFinishedProducts;//成品比例
            obj.partsFinishedProducts=wxpj[i].partsFinishedProducts;//配件比例
            obj.amount=wxpj[i].partsAmount;//配件数量
            obj.costPrice="";//成本单价
            obj.costPriceSubtotal="";//成本小计
            obj.purchaseNo="";//采购单号
            obj.supplierName="";//供应商
            obj.chineseDesc=wxpj[i].productCname;//中文名称
            obj.englishDesc=wxpj[i].productEname//英文名称
            obj.grossWeight=wxpj[i].grossWeight;//毛重
            obj.netWeight=wxpj[i].netWeight;//净重
            obj.volume=wxpj[i].bulk;//体积
            peijianList.push(obj);
        }
        return 0;
    }

}
//通过 外销合同号、产品编码、规格编码获取配件信息
function chanpinbujianData(obj) {
    var objs=[];
    for(var i=0;i<peijianList.length;i++){
        if(salesContractNo==peijianList[i].salesContractNo && peijianList[i].productNo==productNo && peijianList[i].specNo==specNo &&peijianList[i].purchaseType=="2"){
            //pjcb+=peijianList[i].costPrice;

        }
    }
    return objs;
}
//根据外销产品id获取外销产品部件
function getwxbj(id) {
    var obj=[];
    $.ajax({
        type : 'GET'
        //  url : 'resource/getTree',salesContractNo
        ,data:{"id":id },//外销产品id
        url:'exportContract/import/getContractProductPartsById',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj =da.data;
            }
        },
        error: function(data) {
           // layer.msg("获取失败!");
        }
    });
    return obj;
}
//主信息中销售合同号赋值,flag:0=删除；1=插入
function setXSHTH(hth,flag) {
    if(hth.endsWith(",")){
        hth=hth.substr(0,hth.length-1);
    }
    var splits=hth.split(",");
    for(var i=0;i<splits.length;i++){
        var obj=splits[i];
        var tf=true;
        for(var n=0;n<xshth.length ;n++){
            var tem=xshth[n];
            if(tem.name == obj){
                if(flag == 1){
                    tem.cun=tem.cun+1;
                }else{
                    if(tem.cun > 0){
                        tem.cun=tem.cun-1;
                    }else{
                        tem.cun=0;
                    }

                }
                tf=false;
                break;
            }
        }
        if(tf && (flag == 1)){//新插入的销售合同号不在临时变量中,则加入,否则数量加1
            var ob={};
            ob.name=obj;
            ob.cun=1;
            xshth.push(ob);
        }
    }
    var str="";
    for(var i=0;i<xshth.length;i++){
        if(xshth[i].cun > 0){
            str=str+ xshth[i].name+",";
        }
    }
    str=str.substr(0,str.length-1);
    if(flag == 0){
        $("input[name='salesContractNo']")[0].value=str;
    }
    //productList
  return str;
}
function cyjhreshWX(purchaseorderdata,changeList) {
    let ids=purchaseorderdata.map(function(m){return m.id})//ids
    var ht=purchaseorderdata[0];
    var isDeclare=ht.isDeclare;
    businessMode=ht.businessModelCode;//业务模式
    parentCustomerCode=ht.customerCode;//客户编码
    parentCurrencyCode=ht.currencyCode;//币种编码
    parentPriceTermsCode=ht.priceTermsCode;//价格术语编码

    //出运主信息相关字段
    var customerCode=ht.customerCode;//客户编码
    var customerName=ht.customerName;//客户名称
    impcustomerCode=customerCode;
    impcustomerName=customerName;
    var currencyCode=ht.currencyCode;//币种编码
    var priceTermsCode=ht.priceTermsCode;//价格术语编码
    var businessModelCode=ht.businessModelCode;//业务模式
    var bankCode=ht.bankCode;//银行编码
    var signingCompanyCode=ht.signingCompanyCode;//签约公司编码
    var transitPlaceCode=ht.transitPlaceCode;//起运地
    var destinationCode=ht.destinationCode;//目的地
    var paymentTerm=ht.paymentTypeCode;//收款类型

    var transportCode=ht.transportCode;//运输方式编码
    var customerContactName=ht.customerContactName;//客户联系人
    var rmbRate=ht.rmbRate//人民币汇率
    var usdRate=ht.usdRate;//美金汇率

    var salesmanCode=ht.salesmanCode;//业务员
    var salesmanName=ht.salesmanName;//业务员
    var customerAccountingPeriod=ht.customerAccountingPeriod;//帐期

    var billNo="";//ht.billNo;//外销合同号
    var customerContactNo="";//ht.customerContactNo;//客户合同号
    customerContactNo=ht.customerContactNo;


    var whetherCreditGuarantee=ht.whetherCreditGuarantee;//是否走信保订单(0:否 1:是)
    var creditGuaranteeAmount=ht.creditGuaranteeAmount;//信保订单金额USD



    /*for(var i=0;i<purchaseorderdata.length;i++){
        if(i==purchaseorderdata.length-1){
            billNo=billNo+ purchaseorderdata[i].billNo;
            customerContactNo=customerContactNo+purchaseorderdata[i].customerContactNo;
        }else{
            billNo=billNo+ purchaseorderdata[i].billNo+",";
            customerContactNo=customerContactNo+purchaseorderdata[i].customerContactNo+",";
        }

    }*/
    for(var i=0;i<changeList.length;i++){
        var obj=changeList[i];
        var li=changeList[i].changeList;
        if(li.length > 0){
            for(var n=0;n<li.length;n++){

              /* if(n == li.length-1){
                   billNo=billNo+ li[n].billNo;
               }else{
                   billNo=billNo+ li[n].billNo+",";
               }*/
                billNo=billNo+ li[n].billNo+",";
            }
        }
    }

    billNo=setXSHTH(billNo,1);
    var customerLevelName=ht.customerLevelName;
    var customerLevelCode=ht.customerLevelCode;
    getBank(signingCompanyCode);
    if (id == "") {
//主信息赋值
        form.val("editor-form", {
            "customerCode": customerName,
            "companyCode": signingCompanyCode,
            "contactPerson": customerContactName,
            "rmbRate": rmbRate,
            "usdRate": usdRate,
            "salesContractNo": billNo,
            "customerContractNo": customerContactNo,
            "salesmanCode": salesmanCode,
            "salesmanName":salesmanName,
            "currency": currencyCode,
            "priceTerm": priceTermsCode,
            "paymentTerm": paymentTerm,
            "businessMode": businessModelCode,
            "startPlace": transitPlaceCode,
            "endPlace": destinationCode,
            "bankCode": bankCode,
            "payDay": customerAccountingPeriod,
            "customerLevelName": customerLevelName,
            "customerLevelCode": customerLevelCode,
            "transhipment":isDeclare,
            "whetherCreditGuarantee": whetherCreditGuarantee,
            "creditGuaranteeAmount":creditGuaranteeAmount
        })
        if(  transportCode != null){
            form.val("editor-form", {
                "transMode": transportCode
            })
        }
    }else{
        form.val("editor-form", {
            "salesContractNo": billNo
        })
    }
    var purchaseNoString="";//采购单号，用于获取采购单对应的附件
    for(var i=0;i<changeList.length;i++){
       // var cp=changeList[i];
        var cps=changeList[i].changeList;
        for(var n=0;n<cps.length;n++){
            var cp=cps[n];

            var obj={};
            obj.img=cp.img;
            obj.type="1";
            obj.purchaseId=cp.purchaseId;//采购单id
            obj.productId=cp.id;//产品id
            //取采购产品中信息
            obj.purchaseNo=cp.purchaseOrderNo;//采购单号
            purchaseNoString=purchaseNoString+","+obj.purchaseNo;
            obj.amount=cp.productNum;//采购中数量
            obj.grossWeight=cp.grossWeight;//毛重
            obj.netWeight=cp.netWeight;//净重
            obj.volume=cp.volume;//体积
            obj.trayNumber=cp.trayNumber==null?0:cp.trayNumber// 托数
            obj.trayCapacity=cp.trayCapacity==null?0:cp.trayCapacity;// 每托量
            obj.numberOfPiece=cp.numberOfPiece==null?0:cp.numberOfPiece;// 件数
            obj.qty=cp.qty;// 每件数量
            obj.payTime=cp.payTime;//付款账期
            obj.wholeCostPrice=cp.price==null?0:cp.price.toFixed(6);//成品成本     没提供，需补充
            obj.supplierCode=cp.supplierCode;//编码  //供应商     没提供，需补充
            obj.supplierName=cp.supplierName;//名称
            obj.payTime=cp.paymentTime;//帐期
            //取外销产品中信息
            obj.productNo=cp.productCode;//产品编码
            obj.specNo=cp.specificationCode;//规格编码
            obj.normExplain=cp.specificationExplanation;//规格说明
           // obj.customerContractNo=cp.clientProductNo;//客户货号
            obj.customerContractNo=cp.customerContractNo;//客户货号
            obj.chineseName= cp.productCname;//', width: 120, title: '中文名称',edit:'text'},
            obj.englishName= cp.productEname;//', width: 120, title: '英文名称',edit:'text'},
            obj.chineseDesc= cp.productCdesc;//', width: 120, title: '中文描述',edit:'text'},
            obj.englishDesc= cp.productEdesc;//', width: 120, title: '英文描述',edit:'text'},
            obj.colour= cp.color;//', width: 120, title: '颜色',edit:'text'},

            obj.exportContractNo= cp.billNo;//productListin[n].billNO;//', width: 120, title: '外销合同号',edit:'text'},  没提供，需要补充
            obj.outPackLength= cp.outerPackingLong==null?0:cp.outerPackingLong;//', title:'外包装长', width: 120, edit: 'text'},
            obj.outPackWidth= cp.outerPackingWide==null?0:cp.outerPackingWide;//', title:'外包装宽', width: 120, edit: 'text'},
            obj.outPackHeight= cp.outerPackingHeight==null?0:cp.outerPackingHeight;//', title:'外包装高', width: 120, edit: 'text'},

            obj.customerInvoiceGoodsName=cp.customerInvoiceGoodsName
            obj.customerInvoiceSpecModel=cp.customerInvoiceSpecModel
            obj.customerMaterialsCode=cp.customerMaterialsCode

            if(wxandbhflag == "w"){
                obj.accessoryCostPrice=getpeijian(obj.productId,obj.amount, businessModelCode);//配件成本 没提供，需要补充02
            }else{
                obj.accessoryCostPrice=getpeijianBH(obj.productId,cp,"03");
            }

            obj.cpid=cp.id;
            var timestamp=new Date().getTime();
            obj.id="ls"+timestamp+n;

            obj.unit= cp.productUnitName;//', width: 120, title: '单位', templet: '#unitselect'},
            obj.price= cp.unitPrice==null?0:cp.unitPrice;//', width: 80, title: '单价',edit:'text'},
            obj.priceSubtotal=(obj.price*obj.amount).toFixed(2);//金额小计
            obj.grossSubtotal=obj.grossWeight*obj.numberOfPiece;//毛重小计
            obj.netSubtotal=obj.netWeight*obj.numberOfPiece;//净重小计
            if(obj.trayCapacity==0){
                obj.trayNumber=0;
            }else{
                obj.trayNumber=Math.ceil(obj.amount/obj.trayCapacity);//托数
            }
            if(obj.qty==null || obj.qty==0){
                obj.numberOfPiece=0;
            }else{
                obj.numberOfPiece=Math.ceil(obj.amount/obj.qty);//件数
            }


            obj.outPackSize=obj.outPackLength+"*"+obj.outPackWidth+"*"+obj.outPackHeight;//外包装尺寸
            obj.costPrice=(parseFloat(obj.wholeCostPrice)+parseFloat(obj.accessoryCostPrice)).toFixed(6);//成本单价
            obj.costPriceSubtotal=(obj.costPrice*obj.amount).toFixed(2);//成本小计
            obj.remark="";//备注

            productList.push(obj);
        }
    }
    if(!fpzje){
       /* var ia=$("input[name='invoiceAmount']")[0].value;
        if(ia=="" || ia=="Nan"){
            ia=0;
        }*/
        //var am=0;
        var ia=0;
        for(var i=0;i<productList.length;i++){
            ia=parseFloat(  productList[i].priceSubtotal)+parseFloat(ia);
            //ia=parseFloat(  productList[i].priceSubtotal) ;
        }

        $("input[name='invoiceAmount']")[0].value= (parseFloat(ia)+parseFloat(getcostSum())).toFixed(2);
       // $("input[name='invoiceAmount']")[0].value=(parseFloat($("input[name='invoiceAmount']")[0].value) ).toFixed(2);
       // $("input[name='invoiceAmount']")[0].value=(parseFloat($("input[name='invoiceAmount']")[0].value)+getfeiyongjiner()).toFixed(2);
    }


    // layer.msg("OK ");
    table.reload('storageproductstableid', {

        data:productList,limit:productList.length
        /*,page: {
            curr: 1 //重新从第 1 页开始
        }*/

    });
    //导入费用
    importCost(ids)
    //导入采购单附件
    importFile(purchaseNoString);
}
//导入采购单对应的附件
function importFile(purchaseNoString) {
    purchaseNoString="RTCO-2020021804";
    $.ajax({
        type : 'GET'
        //  url : 'resource/getTree',salesContractNo
        ,data:{"purchaseOrderNo":purchaseNoString  },//外销主表id
        url:'purchase/import/getFileByPurchaseOrderNo',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                 var data=da.data;
                 for(var i=0;i<data.length;i++){
                     var obj={};
                     var file=data[i];
                     obj.fileName=file.fileName;
                     obj.size=file.fileSize;
                     obj.type=file.fileType;
                     obj.fileUrl=file.fileUrl;//res.data[0].ftpPath+"/"+res.data[0].fileName;
                     //obj.ftpFileName=res.data[0].fileName;
                     obj.fileUploadTime=timestampToTime(file.fileUploadTime);
                     fujian.push(obj);
                 }
                table.reload('attachmenttableid',{data : fujian});
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });


}
//导入费用
function  importCost(ids) {
    $.ajax({
        type : 'post',
        data:{"ids":JSON.stringify(ids)},
        url:'exportContract/import/getExportContractCostByParentIds',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                let costAmount=new BigNumber(0);
                let objs=[];
                for (let i in da.data) {
                    let obj={};
                    obj.costType=da.data[i].typeCode;
                    obj.costMoney=da.data[i].amount;
                    obj.costDesc=da.data[i].memo;
                    obj.contractNo=da.data[i].contractNo;
                    obj.contractId=da.data[i].id;//外销费用id
                    costAmount=costAmount.plus(new BigNumber(obj.costMoney));
                    objs.push(obj);
                }
                if(objs.length >0){
                    //去除已导入的重复数据
                    objs=objs.filter((item) =>{
                        //原来数组 contractId 集合
                        let contractIdList=feiyong.map(f=>f.contractId);
                        //返回原来数组的 contractId 集合不包含新数组的 contractId 数据 includes() 方法用于判断字符串是否包含指定的子字符串
                        return !contractIdList.includes(item.contractId);
                    })
                    feiyong=feiyong.concat(objs)

                    if(!fpzje){
                        let oldInvoiceAmount=new BigNumber($("input[name='invoiceAmount']")[0].value);
                        $("input[name='invoiceAmount']")[0].value=oldInvoiceAmount.plus(costAmount).toFixed(2);
                    }
                }

            }
        }
    });
    table.reload('costtableid', {
        data:feiyong
        ,page: {
            curr: 1 //重新从第 1 页开始
        }
    }, 'data');
}
//取产品配件, //取配件成本,入参：外销产品id、ms:业务模式
function  getpeijian(wxid,amount,ms) {//配件中，采购产品配件中的producCode=外销配件中的配件编码
    //取采购产品中的配件
    var pjcb=0;//配件成本
    var changeList=[];//配件列表
    //外销配件
    var wxpj=getwxbj(wxid);
    if("1"==ms || "4" === ms){//正常业务、内贸模式
        for(var i=0;i<wxpj.length;i++){
            var wx=wxpj[i];
            var partsCode=wx.partsCode;//配件编码


                    var obj={};
                    obj.type="2";
                    obj.purchaseId=wx.purchaseId;//采购单id
                    obj.productId=wxid;//产品id
                    obj.productNo=partsCode;//外销配件 编码
                    obj.specNo=wx.specNo;//外销规格编码
                    obj.proportionFinishedProducts=wx.proportionFinishedProducts;//外销成品比例
                    obj.partsFinishedProducts=wx.partsFinishedProducts;//外销配件比例
                    obj.supplierName=wx.supplierName;//供应商
                    obj.supplierCode=wx.supplierCode;//供应商编码
                    obj.chineseName=wx.productCname;//中文名称
                    obj.englishName=wx.productEname//英文名称
                    obj.grossWeight=wx.grossWeight;//毛重
                    obj.netWeight=wx.netWeight;//净重
                    obj.volume=wx.bulk;//体积

                    obj.amount=amount*obj.partsFinishedProducts;//配件数量

                    obj.costPrice=wx.price==null?0:wx.price.toFixed(6);//成本单价
                    obj.costPriceSubtotal=(obj.amount*obj.costPrice).toFixed(2);//成本小计
                    obj.purchaseNo=wx.purchaseOrderNo;//采购单号
                    obj.cpid=wxid;//外销产品id

                    pjcb+=parseFloat(obj.costPrice);//配件成本
                    changeList.push(obj);


        }

    }else{//海外业务
        for(var i=0;i<wxpj.length;i++){
            var wx=wxpj[i];
            var obj={};
            obj.type="2";
            obj.productId=wxid;//产品id
            obj.productNo=wx.partsCode;//外销配件 编码
            obj.specNo=wx.specNo;//外销规格编码
            obj.proportionFinishedProducts=wx.proportionFinishedProducts;//外销成品比例
            obj.partsFinishedProducts=wx.partsFinishedProducts;//外销配件比例
           // obj.supplierName=cg.supplierName;//供应商
            obj.chineseDesc=wx.productCname;//中文名称
            obj.englishDesc=wx.productEname//英文名称
            obj.grossWeight=wx.grossWeight;//毛重
            obj.netWeight=wx.netWeight;//净重
            obj.volume=wx.bulk;//体积
//cghts:产品数量
            obj.amount=amount*obj.partsFinishedProducts;//配件数量
//海外模式无成本单价，则写列为0
            obj.costPrice=0;//cghts.toFixed(4);//成本单价
           // obj.costPriceSubtotal=(obj.amount*obj.costPrice).toFixed(2);//成本小计
            //obj.purchaseNo=cg.purchaseOrderNo;//采购单号
            obj.cpid=wxid;//外销产品id

           // pjcb+=parseFloat(obj.costPrice);//配件成本
            changeList.push(obj);
        }


    }
    var jsons = {"productId":wxid,"changeList":changeList};
    peijianList.push(jsons);

return  pjcb;

}
//修改产品数量时更新配件信息
function  getpeijian2(wxid,amount) {//配件中，采购产品配件中的producCode=外销配件中的配件编码
    //取采购产品中的配件
    var pjcb=0;//配件成本
   for(var i=0;i<peijianList.length;i++){
       var pj=peijianList[i];
       if(pj.productId==wxid){
           var data=pj.changeList;
           for(var n=0;n<data.length;n++){
               var obj=data[n];
               obj.amount=amount*obj.partsFinishedProducts;//配件数量
               obj.costPriceSubtotal=obj.amount*obj.costPrice;//成本小计
               pjcb+=parseFloat(obj.costPrice);//配件成本
           }

       }
   }

    return  pjcb.toFixed(6);

}
function wxandbhflag2(flag) {
    wxandbhflag=flag;
}

//取产品配件, //取配件成本,入参：备货产品id、采购合同产品列表;ms:业务模式   导入时用
function  getpeijianBH(wxid,cghts,ms) {//配件中，采购产品配件中的producCode=外销配件中的配件编码
    //取采购产品中的配件
    var pjcb=0;//配件成本
    var changeList=[];//配件列表
    //外销配件
    var wxpj=getbhbj(wxid);

        for(var i=0;i<wxpj.length;i++){
            var wx=wxpj[i];
            var partsCode=wx.partsCode;//配件编码
           // for(var n=0;n<cghts.length;n++){//采购产品列表
               // var cg=cghts[n];//采购产品
                //var cgtype=cghts[n].purchaseType;//采购类型，1：产品；2：配件

               // if("2"==cgtype && partsCode==cg.productNo) {//配件
                    var obj={};
                    obj.type="2";
                    obj.purchaseId=wx.purchaseId;//采购单id
                    obj.productId=wxid;//产品id
                    obj.productNo=partsCode;//外销配件 编码
                    obj.specNo=wx.specNo;//外销规格编码
                    obj.proportionFinishedProducts=wx.proportionFinishedProducts;//外销成品比例
                    obj.partsFinishedProducts=wx.partsFinishedProducts;//外销配件比例
                    obj.supplierName=wx.supplierName;//供应商
                    //供应商编码
                    obj.supplierCode=wx.supplierCode;
                    obj.chineseName=wx.productCname;//中文名称
                    obj.englishName=wx.productEname//英文名称
                    obj.grossWeight=wx.grossWeight;//毛重
                    obj.netWeight=wx.netWeight;//净重
                    obj.volume=wx.bulk;//体积

                    obj.amount=cghts.productNum*obj.partsFinishedProducts;//配件数量

                    obj.costPrice=wx.price.toFixed(6);//配件成本单价
                    obj.costPriceSubtotal=(obj.amount*obj.costPrice).toFixed(2);//成本小计
                    obj.purchaseNo=wx.purchaseOrderNo;//采购单号
                    obj.cpid=wxid;//外销产品id

                    pjcb+=parseFloat(obj.costPrice);//配件成本
                    changeList.push(obj);
               // }
           // }
        }
    var jsons = {"productId":wxid,"changeList":changeList};
    peijianList.push(jsons);

    return  pjcb;
}
//根据备货产品id获取备货产品部件，导入时用
function getbhbj(id) {
    var obj=[];
    $.ajax({
        type : 'GET'
        //  url : 'resource/getTree',salesContractNo
        ,data:{"id":id },//外销产品id
      //  url:'task/import/getTaskProductPartsByPage',
        url:'task/import/getTaskProductParts',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj =da.data;
            }
        },
        error: function(data) {
           // layer.msg("获取失败!");
        }
    });
    return obj;
}

//获取货柜型号
function getContainerModel(){

    $.ajax({
        url:"offer/getContainerModel",
        async:false,
        success:function(data){
            if(data.status == 200){
                containerModel = data.data;
                for(let i in data.data){
                    $('#containerTypeCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });
}
function isContainerNum() {
    let num=$('#containerNum').val();
    if ((/(^[0-9]\d*$)/.test(num))) {
        return true;
    }else {
        layer.msg("请输入整数");
        $("#containerNum").focus();
        return false;
    }
}
function getIsContainsRoleShipPlan(){
    $.ajax({
        url: 'shipmentPlan/isContainsRoleShipPlan',
        async: false, // 同步
        success: function (data) {
            if (data.status==200){
                isContainsRoleShipPlan=data.data;
            }
        }
    });
}

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now())
}
